/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SessionBeans.actions;

import SessionBeans.entites.FileService;
import api.action.crates.Server.NewFileCrate;
import api.exception.TCloudAplicationException;
import entities.AccountHeader;
import entities.Folder;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Tomas
 */
@Stateless(name="NEW_FILE")
@LocalBean
public class NewFileService implements InvokeActionInterface<NewFileCrate> {
    @EJB
    private FileService fileService;

    @PersistenceContext(unitName = "tCloudEE-ejbPU")
    private EntityManager em;

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")   

    @Override
    public void processAction(NewFileCrate actionData, Long userId, AccountHeader accHeader) throws TCloudAplicationException {
        em.refresh(accHeader.getRootFolder());
        if(Utils.findFile(accHeader.getRootFolder(), actionData.getPath()) != null){
            throw new TCloudAplicationException(100, actionData.getPath());
        }
        
        Folder parentFolder = Utils.findParentFolder(accHeader.getRootFolder(), actionData.getPath());

        fileService.newFile(userId, Utils.getNameFromPath(actionData.getPath()), actionData.getValue(), parentFolder);        
        
    }
}
